<?php


namespace app\api\controller;
use app\admin\controller\Addon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use WechatPay\GuzzleMiddleware\WechatPayMiddleware;
use WechatPay\GuzzleMiddleware\Util\PemUtil;
use GuzzleHttp\HandlerStack;

class HttpClient extends Addon
{
    protected $client;

    public function _initialize()
    {
        // 商户相关配置，
        $merchantId = '1621457307'; // 商户号
        $merchantSerialNumber = 'XXXXXXXXXX'; // 商户API证书序列号
        $merchantPrivateKey = PemUtil::loadPrivateKey('apiclient_key.pem'); // 商户私钥文件路径

        // 微信支付平台配置
        $wechatpayCertificate = PemUtil::loadCertificate('apiclient_cert.pem'); // 微信支付平台证书文件路径


        // 构造一个WechatPayMiddleware
        $wechatpayMiddleware = WechatPayMiddleware::builder()
            ->withMerchant($merchantId, $merchantSerialNumber, $merchantPrivateKey) // 传入商户相关配置
            ->withWechatPay([ $wechatpayCertificate ]) // 可传入多个微信支付平台证书，参数类型为array
            ->build();


        // 将WechatPayMiddleware添加到Guzzle的HandlerStack中
        $stack = HandlerStack::create();
        $stack->push($wechatpayMiddleware, 'wechatpay');


        // 创建Guzzle HTTP Client时，将HandlerStack传入，接下来，正常使用Guzzle发起API请求，WechatPayMiddleware会自动地处理签名和验签
        $this->client = new Client(['handler' => $stack]);
        parent::_initialize(); // TODO: Change the autogenerated stub
    }


    public function pay(){
        try {
            $resp = $this->client->request(
                'POST',
                'https://api.mch.weixin.qq.com/v3/pay/partner/transactions/jsapi', //请求URL
                [
                    // JSON请求体
                    'json' => [
                        "sp_mchid"=>  "1900007XXX",
                        "sub_mchid"=> "1900008XXX",
                        "out_trade_no"=>  "1217752501201407033233368318",
                        "sp_appid"=>  "wxdace645e0bc2cXXX",
                        "sub_appid"=>  "wxdace645e0bc2cXXX",
                        "description"=>  "Image形象店-深圳腾大-QQ公仔",
                        "notify_url"=>  "https://weixin.qq.com/",
                        "amount"=> [
                            "total"=>1,
                            "currency"=>  "CNY"
                        ],
                        "payer"=> [
                            "sp_openid"=> "o4GgauInH_RCEdvrrNGrntXDuXXX"
                        ]
                    ],
                    'headers' => [ 'Accept' => 'application/json' ]
                ]
            );
            $statusCode = $resp->getStatusCode();
            if ($statusCode == 200) { //处理成功
                echo "success,return body = " . $resp->getBody()->getContents()."\n";
            } else if ($statusCode == 204) { //处理成功，无返回Body
                echo "success";
            }
        } catch (RequestException $e) {
            // 进行错误处理
            echo $e->getMessage()."\n";
            if ($e->hasResponse()) {
                echo "failed,resp code = " . $e->getResponse()->getStatusCode() . " return body = " . $e->getResponse()->getBody() . "\n";
            }
            return;
        }
    }
}